//**************************************************************************
// MIPS Regfile
//--------------------------------------------------------------------------
//
// zyk

package openmips.id

import chisel3._
import chisel3.util._

import openmips.utils.Config._

class RegRead extends Bundle {
    val data = Output(UInt(32.W))
    val addr = Input(UInt(5.W))
    val enable = Input(Bool())
}

class RegWrite extends Bundle {
    val data = Input(UInt(32.W))
    val addr = Input(UInt(5.W))
    val enable = Input(Bool())
}

class RegfileIo extends Bundle {
    val read = Vec(2, new RegRead())
    val write = new RegWrite()
}

class Regfile extends Module {
    val io = IO(new RegfileIo())
    io := DontCare

    // 创建寄存器并初始化
    val regfile = RegInit(VecInit(Seq.fill(32)(0.U(32.W))))

    // 同步写，异步读
    when(io.write.enable) {
        // 这里没有跳过0号寄存器
        regfile(io.write.addr) := io.write.data
    }

    for (i <- 0 to 1) {
        when(io.read(i).addr === 0.U) {
            io.read(i).data := 0.U
        }
        .elsewhen(io.read(i).enable && io.read(i).addr === io.write.addr && io.write.enable) {
            io.read(i).data := io.write.data
        }
        .elsewhen(io.read(i).enable) {
            io.read(i).data := regfile(io.read(i).addr)
        }
        .otherwise {
            io.read(i).data := 0.U
        }
    }
}

object Regfile extends App {
    Driver.execute(Array("--target-dir", OUTPUT_DIR), () => new Regfile)
}